// 系统日志收集

const { failRes, successRes } = require('../extend/helper');

exports.Journal = async (ctx, { params = null, operatorType, code }) => {
  try {
    if (ctx.request.method === 'OPTIONS') return;
    const agent = ctx.request.headers['user-agent'] || ''; // 代理
    const ipAddress = ctx.request.ip || ''; // ip地址
    const clientType = ctx.request.headers['allocation'] || ''; // 来源 allocation
    // -----
    let submitInfo = ''; // 提交信息
    if (ctx.request.method === 'GET') {
      submitInfo = ctx?.query ?? {};
    } else {
      submitInfo = ctx?.request?.body ?? {};
    }
    submitInfo = params ? (JSON.stringify(params)) : (JSON.stringify(submitInfo) === '{}' ? '' : JSON.stringify(submitInfo));
    // ------
    let operatorErr = {};
    let operatorState = true;
    if (code === 200) {
      operatorState = true;
    } else {
      operatorState = false;
      operatorErr = failRes(code);
    }
    operatorErr = JSON.stringify(operatorErr) === '{}' ? '' : JSON.stringify(operatorErr);
    await ctx.model.Journal.create({
      Ip: ipAddress,
      Source: clientType,
      Type: operatorType,
      Submit: submitInfo,
      Url: ctx?.request?.url??'',
      Agent: agent,
      State: operatorState,
      Err: operatorErr,
    });
  } catch (error) {
    console.error('写入日志出错', error);
  }
}